<?php

namespace App\Http\Controllers\Wechat\Plugins;

use Laravel\Lumen\Routing\Controller as BaseController;
use App\Http\Controllers\Wechat\Messages;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;


class ExpressTracking extends BaseController
{
    public static function push($message)
    {
        preg_match('/(\d+)/', $message->Content, $number);    // 单号
        preg_match('/\d+(.+)/', $message->Content, $note);    // 用户添加的快递备注
        if (strlen($note[1]) == 1) {    // 没有备注时 备注会匹配到单号的最后一位
            $note[1] = null;
        }

        self::doTracking($message->FromUserName, $number[1], $note[1]);
    }

    /**
     * 快递物流信息插入数据库
     * @param $message
     * @param $data
     */
    private static function insertDb($openid, $data, $note)
    {
        $modelExpress = new \App\Models\Express;

        $modelExpress->openid  = $openid;
        $modelExpress->nu      = $data['nu'];
        $modelExpress->state   = $data['state'];
        $modelExpress->context = $data['data'][0]['context'];
        $modelExpress->time    = $data['data'][0]['time'];
        $modelExpress->com     = $data['com'];
        $modelExpress->message = $data['message'];
        $modelExpress->note    = $note;
        $modelExpress->url     = $data['url'];

        $modelExpress->save();

        return $modelExpress;
    }

    /**
     * 加入快递追踪服务
     * @param $message
     * @param $data
     * @return mixed
     */
    private static function joinServiceNotice($openid, $data, $note)
    {
        return Messages\Notices::expressTracking(
            $openid,
            "已加入快递追踪服务!\n",
            $data['nu'],
            $data['data'][0]['context'],
            $data['data'][0]['time'],
            "\n您将实时收到快递最新状态!\n备注：$note".' ['.$data['com'].']',
            $data['url']
        );
    }


    /**
     * 点击 快递追踪 按钮后触发的事件
     * @param $message
     * @return array
     */
    public static function click($message)
    {
        return Messages\News::expressTracking();
    }

    /**
     * 网页 快递查询
     */
    public static function expressHtml()
    {
        $app    = new Application(config('wechat'));
        $user   = $app->oauth->user();
        $openid = $user->id;

        return view('wechat.express')->with('id', $openid);
    }

    /**
     * 网页 快递查询结果
     */
    public static function expressPost(Request $request)
    {
        $openid = $request->get('id');
        $nu     = $request->get('nu');
        $note   = $request->get('note');

        $doRes = self::doTracking($openid, $nu, $note, 'html');

        return view('wechat.expressres')->with('res', $doRes);
    }


    private static function doTracking($openid, $nu, $note, $from = 'commond')
    {
        $queryResult = (new \Xu42\ExpressTracking\ExpressTracking($nu))->latestStatus();

        if ($queryResult['status'] != 200) {
            if ($from == 'commond') {
                return Messages\Text::wrongExpress($queryResult['url']);
            }
            if ($from == 'html') {
                return false;
            }
        }

        if (($queryResult['status'] == 200) && ($queryResult['state'] != 3)) {
            $express = self::insertDb($openid, $queryResult, trim($note));
            self::joinServiceNotice($openid, $queryResult, trim($note));
            if ($from == 'html') {
                return true;
            }
        }

        if (($queryResult['status'] == 200) && ($queryResult['state'] == 3)) {
            if ($from == 'commond') {
                return Messages\Text::receiptExpress($queryResult['data'][0]['context'], $queryResult['url']);
            }
            if ($from == 'html') {
                return false;
            }
        }
    }

}